from flask import Flask, request, jsonify,make_response
from langchain_community.chat_models import ChatOpenAI
from langchain.schema import HumanMessage
from pymongo import MongoClient
from bson import ObjectId
import json
import os
from datetime import datetime

app = Flask(__name__)

# 设置 API 配置
api_key = "sk-374d28568f82479b89cdbaa74cac4c06"  # 替换为你的 API Key
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"

# 创建 LangChain 的 ChatOpenAI 实例
chat = ChatOpenAI(
    model="deepseek-r1",
    openai_api_key=api_key,
    openai_api_base=base_url,
    temperature=0.7
)

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        elif isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        return super().default(o)

app.json_encoder = CustomJSONEncoder

def convert_values_to_string(data):
    if isinstance(data, dict):
        return {key: convert_values_to_string(value) for key, value in data.items()}
    elif isinstance(data, list):
        return [convert_values_to_string(item) for item in data]
    else:
        return str(data)

@app.route('/get_post', methods=['GET'])
def get_post():
    post_id = request.args.get('id')
    if not post_id:
        return jsonify({"error": "缺少必要参数 'id'"}), 400

    print(post_id)

    try:
        client = MongoClient('mongodb://127.0.0.1:27017/')
        db = client['test']
        collection = db['posts']

        try:
            object_id = ObjectId(post_id)
            print(object_id)
            post = collection.find_one({"_id": object_id})
            print(post)

            if post:
                post_with_string_values = convert_values_to_string(post)
                print(post_with_string_values)
                print(2333)
                # 将字典转换为字符串后再拼接
                post_str = json.dumps(post_with_string_values)
                print(post_str)
                messages = [
                    HumanMessage(content=post_str + "这里给出的是文章的详细信息，要求，通过给出的文章的详细信息，生成出这一篇文章的相关摘要。")
                ]

                print(messages)

                # 获取响应
                response = chat(messages)

                # 打印响应
                print("完整响应：")
                print(response)

                # 直接返回 content 部分给前端
                if hasattr(response, 'content'):
                    response_data = {"summary": response.content}
                    # 创建响应对象并指定编码为 UTF-8
                    resp = make_response(jsonify(response_data))
                    resp.headers['Content-Type'] = 'application/json; charset=utf-8'
                    return resp
                else:
                    return jsonify({"error": "未获取到有效的摘要内容"}), 500



                # # 打印思考过程（如果模型支持）
                # if hasattr(response, 'reasoning_content'):
                #     print("\n思考过程：")
                #     print(response.reasoning_content)

                # # 打印最终答案
                # print("\n最终答案：")
                #return jsonify(post_with_string_values)
            else:
                return jsonify({"error": "未找到对应的文章。"}), 404
        except Exception as e:
            return jsonify({"error": f"无效的 _id 格式: {e}"}), 400

    except Exception as e:
        return jsonify({"error": f"连接或读取 MongoDB 时出错: {e}"}), 500
    finally:
        if 'client' in locals():
            client.close()


if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)